<template>
  <el-drawer
    :class="[fullScreen ? 'full-screen' : '']"
    :visible.sync="drawer"
    :direction="direction"
    :size="drwerSize"
    @close="close"
    class="je-drawer"
    append-to-body
    destroy-on-close
    custom-class="je-drawer-modal"
  >
    <template #title>
      <!-- 标题 -->
      <div
        v-if="currentTab == '1'"
        class="itemview-header"
      >
        <div class="message-status">
          <div
            :class="{active:activeStatus==item.code}"
            @click="activeStatus=item.code;"
            v-for="item in status"
            :key="item"
            class="item"
          >
            {{ item.text }}
            <span>({{ item.count }})</span>
          </div>
        </div>
      </div>
      <div
        v-if="currentTab == '0'"
        class="postilTitle"
      >
        {{ $t('m.weiyou_publish') }}
      </div>
    </template>

    <el-tabs
      :tab-position="'left'"
      @tab-click="handleTabsClick"
      class="leftTabs"
      lazy
    >
      <el-tab-pane ref="tabPostil">
        <span
          slot="label"
          :style="{'padding-top': getNum(postilNum) == 0 ? '10px': 0,'width': getNum(postilNum) == 0 ? '18px': '27px'}"
          class="je-postil"
        >
          {{ $t('m.weiyou_postil') }}
          <el-badge
            :value="getNum(postilNum)"
            :hidden="getNum(postilNum) == 0"
            :max="99"
            class="mark"
          />
        </span>

        <je-vue-postil
          ref="jePostil"
          :params="params"
          @lookdetail="lookdetail"
          @getPostilNum="refreshBadge"
        />
      </el-tab-pane>
      <el-tab-pane
        ref="tabMail"
        v-if="params.showMail"
      >
        <span
          slot="label"
          :style="{'padding-top': getNum(allCount) == 0 ? '10px': 0,'width': getNum(allCount) == 0 ? '18px': '27px'}"
          class="je-mail"
        >
          {{ $t('m.weiyou_micromail') }}
          <el-badge
            :value="getNum(allCount)"
            :hidden="getNum(allCount) == 0"
            :max="99"
            class="mark"
          />
        </span>

        <div class="itemview-body">
          <query-condition @getSearchParams="getSearchParams">
            <template #otherQuery>
              <el-checkbox-group
                v-model="checkedQuerys"
                :min="0"
                :max="3"
                class="mail-checkbox"
              >
                <el-checkbox
                  v-for="(item,index) in querys"
                  :label="item.text"
                  :key="index"
                >
                  {{ item.text }}
                </el-checkbox>
              </el-checkbox-group>
            </template>
          </query-condition>
          <!-- 列表 -->
          <div
            :style="{'height': listHeight}"
            v-infinite-scroll="loadMore"
            :infinite-scroll-disabled="disabled"
            class="mail-list"
          >
            <mail-item
              v-for="(item, index) in mailList"
              v-on="$listeners"
              @deleteMail="deleteMail(index)"
              @newComment="addNewComment"
              @setReaded="setReaded"
              @doFocus="doFocus"
              :key="index"
              :mailItem="item"
              :themeWidth="itemWidth"
            />
            <p
              v-if="loading"
              class="list-loading"
            >
              {{ $t('m.weiyou_loading') }}
            </p>
            <Nodata v-if="noData" />
            <!-- <p
              v-if="noMore"
              class="list-nomore"
            >
              没有更多了
            </p> -->
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <el-button
      v-if="currentTab == '1'"
      @click="openCreate"
      class="addBtn"
      type="text"
      icon="jeicon jeicon-new-fine-plus-circle"
    />
    <create-mail
      ref="createMails"
      :handleType="'create'"
      :params="params"
      v-on="$listeners"
      @doCreate="doCreate"
    />
  </el-drawer>
</template>

<script>
import VueI18n from 'vue-i18n';
import MailItem from '../../modules/microMail/component/mail_item';
import QueryCondition from '../../modules/microMail/component/queryCondition';
import CreateMail from '../../modules/microMail/component/create';
import {
  getMyMailList, getTotalCount, getTypeTotalCount,
} from '../../modules/microMail/actions/actions';
import JeVuePostil from './component/postil/postil';
import Nodata from '../noData/index';

import getMaxZindex from '../../modules/microMail/util/getZindex';

const i18n = new VueI18n({
  locale: JE.getCookies('je-local-lang') || 'zh_CN', // 语言标识
  messages: {
    zh_CN: require('../../modules/microMail/assets/lang/zh'), // 中文语言包
    en: require('../../modules/microMail/assets/lang/en'), // 英文语言包
  },
});

export default {
  name: 'Cooperation',
  components: {
    MailItem, QueryCondition, CreateMail, JeVuePostil, Nodata,
  },
  i18n,
  props: {
    params: {
      type: Object,
      default: () => ({
        visible: false,
        funcCode: '',
        pkValue: '',
        bean: {},
        showMail: true, // 是否显示微邮
        showOtherBtn: false, // 是否展示查看详情按钮
      }),
    },
  },
  data() {
    return {
      loading: false,
      drawer: false,
      drwerSize: '820px',
      direction: 'rtl',
      status: [
        { text: '我收到的', code: '1', count: 0 },
        { text: '我发出的', code: '2', count: 0 },
      ],
      activeStatus: '1',
      unreadCount: 0,
      focusCount: 0,
      querys: [
        { text: '已读' },
        { text: '未读' },
        { text: '心标' },
      ],
      checkedRule: '1',
      checkedQuerys: [],
      startTime: '', // 开始时间
      endTime: '', // 结束时间
      keyword: '', // 关键字查询
      pageSize: 30,
      pageNumber: 0,
      fullScreen: false,
      listHeight: '590px',
      itemWidth: '630px',
      mailList: [],
      tabZindex: 11,
      currentTab: '0',
      postilNum: 0, // 批注角标数量
      noMore: false, // 没有更多数据
      noData: false, // 没有数据
      allCount: 0,
    };
  },
  computed: {
    disabled() {
      return this.loading || this.noMore;
    },
    getNum() {
      return (num) => {
        const realNum = Number(num);
        return realNum > 99 ? 99 : realNum;
      };
    },
  },
  watch: {
    fullScreen(nv) {
      setTimeout(() => {
        this.listHeight = `${document.getElementsByClassName('je-drawer')[0].offsetHeight - 100}px`;
        this.itemWidth = nv ? '1020px' : '630px';
      }, 20);
    },
    activeStatus() {
      this.pageNumber = 1;
      this.mailList = [];
      this.loadMailList();
    },
    drawer(nv) {
      this.getAllCount();
      this.$nextTick(() => {
        if (nv) {
          setTimeout(() => {
            $('.je-drawer').css({ 'z-index': getMaxZindex() + 2 });
            $('.v-modal').css({ 'z-index': getMaxZindex() - 1 });
          }, 100);
          this.$refs.jePostil && this.$refs.jePostil.initEditor();
        } else {
          this.$refs.jePostil && this.$refs.jePostil.UEditor && this.$refs.jePostil.UEditor.destroy();
        }
      });
    },
    currentTab(nv) {
      if (nv == '1') {
        this.initCount();
        this.$nextTick(() => {
          this.listHeight = `${document.getElementsByClassName('je-drawer')[0].offsetHeight - 100}px`;
        });
      }
    },
    checkedQuerys: {
      handler(nv) {
        if (nv.length == 0) {
          this.checkedRule = '1';
        }
        nv.length == 1 && nv.forEach((item) => {
          if (item == '已读') {
            this.checkedRule = '2';
          } else if (item.includes('未读')) {
            this.checkedRule = '3';
          } else if (item.includes('心标')) {
            this.checkedRule = '4';
          }
        });
        if (nv.length == 3) {
          this.checkedRule = '4';
        }

        if (nv.length == 2 && nv.join(',').includes('已读') && nv.join(',').includes('未读')) {
          this.checkedRule = '1';
        }

        if (nv.length == 2 && nv.join(',').includes('心标') && nv.join(',').includes('已读')) {
          this.checkedRule = '5';
        }
        if (nv.length == 2 && nv.join(',').includes('心标') && nv.join(',').includes('未读')) {
          this.checkedRule = '6';
        }
        this.pageNumber = 1;
        this.mailList = [];
        this.loadMailList();
      },
      deep: true,
    },
  },
  mounted() {
    this.drawer = this.params.visible;
  },
  methods: {
    lookdetail() {
      this.drawer = false;
      this.params.visible = false;
    },
    close() {
      $('.v-modal').hide();
      this.params.visible = false;
      this.drawer = false;
    },
    // 刷新批注角标
    refreshBadge(num) {
      this.postilNum = num;
      this.$emit('callback', Number(this.allCount) + Number(this.postilNum));
    },
    getAllCount() {
      getTotalCount({
        modelId: this.params.pkValue,
      }).then((data) => {
        // if (data.success) {
        this.allCount = data.totalCount;
        // }
      });
    },
    setReaded() {
      this.initCount();
    },
    // 获取未读数量的角标数值
    initCount() {
      this.pageNumber = 1;
      this.mailList = [];
      this.getAllCount();
      getTypeTotalCount({
        modelId: this.params.pkValue,
      }).then((data) => {
        // if (data.success) {
        this.status[0].count = data.obj.receive;
        this.status[1].count = data.obj.send;
        // this.status[2].count = data.obj.attention;
        // }

        this.loadMailList(); // 调数据列表接口
      });
    },
    // 关注收藏
    doFocus() {
      this.initCount();
    },
    // 删除微邮
    deleteMail(index) {
      this.mailList.splice(index, 1);
      this.initCount();
      setTimeout(() => {
        this.$emit('callback', Number(this.allCount) + Number(this.postilNum));
      }, 1000);
    },
    // 获取参数
    getParams() {
      return {
        keyword: this.keyword,
        modelId: this.params.pkValue,
        startTime: this.startTime,
        endTime: this.endTime,
        type: this.activeStatus,
        readType: this.checkedRule,
        limit: this.pageSize,
        pageNumber: this.pageNumber,
      };
    },
    getSearchParams(param) {
      this.keyword = param.keyword;
      this.startTime = param.startTime;
      this.endTime = param.endTime;
      this.pageNumber = 1;
      this.mailList = [];
      this.loadMailList();
    },
    // 加载数据
    loadMailList() {
      this.noData = false;
      getMyMailList(this.getParams()).then((data) => {
        if (data.success) {
          this.loading = false;
          this.unreadCount = data.noReadCount;
          this.focusCount = data.gzCount;
          this.querys = [
            { text: '已读' },
            { text: `未读 (${this.unreadCount == undefined ? 0 : this.unreadCount})` },
            { text: `心标 (${this.focusCount == undefined ? 0 : this.focusCount})` },
          ];
          if (data.rows.length == 0) {
            this.noData = true;
            this.noMore = false;
          }
          if (data.rows.length < 30) {
            this.noMore = true;
          }
          this.mailList = data.rows;
        }
      });
    },
    // 滚动加载更多
    loadMore() {
      if (this.currentTab == '1') {
        setTimeout(() => {
          this.loading = true;
          this.pageNumber += 1;
          getMyMailList(this.getParams()).then((data) => {
            if (data.success) {
              this.loading = false;
              if (data.rows.length < 30) {
                this.noMore = true;
              }
              this.mailList = this.mailList.concat(data.rows);
            }
          });
        }, 1000);
      }
    },
    // 打开新建微邮
    openCreate() {
      this.$refs.createMails.dialogVisible = true;
    },
    // 新建微邮
    doCreate() {
      this.initCount();
      setTimeout(() => {
        this.$emit('callback', Number(this.allCount) + Number(this.postilNum));
      }, 1000);
    },
    // 发新评论
    addNewComment() {
      this.initCount();
    },
    //  全屏
    changeFullScreen(fullScreen) {
      this.fullScreen = fullScreen;
    },
    // 左侧tabs切换
    handleTabsClick(tab) {
      this.currentTab = tab.index;
      setTimeout(() => {
        if (this.tabZindex < 1000) {
          this.tabZindex += 1;

          if (tab.index === '0') {
            document.getElementsByClassName('el-tabs__item is-left')[0].style.zIndex = this.tabZindex;
          } else if (tab.index === '1') {
            document.getElementsByClassName('el-tabs__item is-left')[1].style.zIndex = this.tabZindex;
          }
        } else {
          this.tabZindex -= 2;
          if (tab.index === '0') {
            document.getElementsByClassName('el-tabs__item is-left')[1].style.zIndex = this.tabZindex;
          } else if (tab.index === '1') {
            document.getElementsByClassName('el-tabs__item is-left')[0].style.zIndex = this.tabZindex;
          }
        }
      }, 100);
    },
  },
};
</script>

<style lang="scss">
.je-drawer {
  top: 50px;
  overflow: inherit;
  .el-badge__content {
    height: 20px;
    line-height: 16px;
  }
  .je-drawer-modal {
    border-top-left-radius: 6px;
    overflow: inherit;
    .el-drawer__header {
      margin-bottom: 5px;
      padding: 5px 20px 0;
      padding-left: 30px;
      overflow: hidden;
    }
  }
  .postilTitle {
    font-size: 16px;
    color: #444;
    height: 50px;
    font-weight: 600;
    line-height: 50px;
  }
  .itemview-header {
    position: relative;
    font-size: 16px;
    color: #444;
    height: 50px;
    line-height: 50px;
    font-weight: 600;
    float: left;
    .message-status {
      .item {
        display: inline-block;
        line-height: 30px;
        font-weight: 600;
        height: 30px;
        padding-right: 20px;
        cursor: pointer;
        &.active {
          color: #386ad0;
        }
      }
    }
  }
  .el-drawer__close-btn {
    float: right;
    height: 50px;
  }
  .itemview-body {
    position: relative;
    .mail-checkbox {
      display: inline-block;
      margin-left: 30px;
    }
    .mail-list {
      height: 590px;
      overflow-y: auto;
      position: relative;
      .list-loading,
      .list-nomore {
        height: 40px;
        line-height: 40px;
        text-align: center;
        color: #999;
        font-size: 14px;
      }
    }
  }
  .full-screen {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 100;
    animation: unset;
    background: #f0f2f5;
    .je-drawer {
      background: #ffffff;
      position: relative;
      width: 1250px;
      margin: 0 auto;
      height: 100%;
    }
  }

  .leftTabs {
    overflow: inherit;
    .el-tabs__header.is-left {
      float: inherit;
      position: absolute;
      top: 17px;
      left: -56px;
      margin-right: 0;
      height: auto;
      width: 56px;
      height: 300px;
    }
    .el-tabs__nav-wrap::after {
      width: 0;
    }
    .el-tabs__active-bar.is-left {
      width: 0;
    }
    .el-tabs__item.is-left {
      text-align: center;
      height: 122px;
      color: #444444;
      padding: 0 8px;
      padding-top: 32px;
      padding-left: 5px;
      background: url("./assets/img/tabBg.png") no-repeat;
      position: absolute;
      top: 0;
      left: 19px;
      width: 42px;
      z-index: 10;
      .je-postil,
      .je-mail {
        width: 27px;
        font-weight: 500;
        margin: 0 auto;
        line-height: 20px;
        font-size: 18px;
        display: inline-block;
        white-space: normal;
      }
    }
    .el-tabs__item.is-active {
      color: #386ad0;
      background: url("./assets/img/tabBg-active.png") no-repeat;
    }
    .el-tabs__item:hover {
      color: #386ad0;
      cursor: pointer;
      background: url("./assets/img/tabBg-active.png") no-repeat;
    }
    #tab-0 {
      z-index: 11;
    }
    #tab-1 {
      top: 100px;
    }
  }

  .addBtn {
    box-shadow: 0px 5px 12px 0px rgba(83, 109, 254, 0.44);
    position: absolute;
    color: #386ad0;
    right: 61px;
    bottom: 162px;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    padding: 0;
    line-height: 0.8;
    .jeicon-new-fine-plus-circle {
      font-size: 52px;
      margin-left: -2px;
    }
    &:hover {
      color: #409eff;
    }
  }
}
</style>
